package net.pingfang.devicelock;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import lombok.extern.slf4j.Slf4j;
import net.pingfang.devicelock.Decoder.HHDDecoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


@Configuration
@Slf4j
public class NettyClientConfig {

    @Value("${device.lock.hhd.port}")
    private int port;

    @Value("${device.lock.hhd.host}")
    private String host;

    private EventLoopGroup workerGroup;
    private Channel channel;
    private final AtomicInteger reconnectAttempts = new AtomicInteger(0);
    private final int MAX_RECONNECT_ATTEMPTS = 2; // 最大重试次数

    @Bean(destroyMethod = "shutdown")
    public EventLoopGroup workerGroup() {

        if (workerGroup == null) {
            workerGroup = new NioEventLoopGroup();
        }
        return workerGroup;
    }

    //.remoteAddress(host, port)
    @Bean
    @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Bootstrap bootstrap(EventLoopGroup workerGroup) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) // 连接超时5秒
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline()
                                .addLast(new HHDDecoder())
                                .addLast(new ByteArrayEncoder())
                                .addLast(new ByteArrayDecoder())
                                .addLast(new NettyClientHandler());
                    }
                });
        // 确保使用已注入的值设置远程地址
        bootstrap.remoteAddress(host, port);
        return bootstrap;
    }

    @Bean
    @Lazy
    public Channel nettyChannel(Bootstrap bootstrap) {
        connectWithRetry(bootstrap);
        return channel;
    }

    /**
     * 带重试机制的连接方法
     */
    private void connectWithRetry(Bootstrap bootstrap) {
//        bootstrap.remoteAddress(host, port);
        connect(bootstrap);
    }

    private void connect(Bootstrap bootstrap) {
        if (reconnectAttempts.get() >= MAX_RECONNECT_ATTEMPTS) {
            log.error("Maximum reconnect attempts ( {}) reached. Giving up.",MAX_RECONNECT_ATTEMPTS);
            return;
        }

        ChannelFuture future = bootstrap.connect();
        future.addListener((ChannelFutureListener) f -> {
            if (f.isSuccess()) {
                log.info("Connected to {} : {} " , host , port);
                channel = f.channel();
                reconnectAttempts.set(0); // 重置重试计数器

                // 添加连接关闭监听器
                channel.closeFuture().addListener(closeFuture -> {
                    if (reconnectAttempts.get() < MAX_RECONNECT_ATTEMPTS) {
                        log.info("Connection closed. Reconnecting...");
                        reconnectAttempts.incrementAndGet();
                        scheduleReconnect(bootstrap);
                    } else {
                        log.info("Max reconnect attempts reached after disconnection");
                    }
                });
            } else {
                log.error("Failed to connect:{} " , f.cause().getMessage());
                reconnectAttempts.incrementAndGet();
                if (reconnectAttempts.get() <= MAX_RECONNECT_ATTEMPTS) {
                    scheduleReconnect(bootstrap);
                } else {
                    log.info("Max reconnect attempts reached");
                }
            }
        });
    }

    /**
     * 调度重连任务
     */
    private void scheduleReconnect(Bootstrap bootstrap) {
        if (reconnectAttempts.get() > MAX_RECONNECT_ATTEMPTS) {
            log.error("Maximum reconnect attempts reached. Not reconnecting.");
            return;
        }

        int delaySeconds = 5; // 5秒后重试
        log.info("Scheduling reconnect in {} seconds (attempt {} / {} ) " , delaySeconds ,
                reconnectAttempts.get() ,MAX_RECONNECT_ATTEMPTS );

        bootstrap.config().group().schedule(() -> connect(bootstrap), delaySeconds, TimeUnit.SECONDS);
    }

    @PreDestroy
    public void shutdown() {
        if (channel != null && channel.isActive()) {
            channel.close();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        log.info("Netty client resources released");
    }

//    @Bean
//    public Bootstrap bootstrap(EventLoopGroup workerGroup) {
//        return new Bootstrap()
//                .group(workerGroup)
//                .channel(NioSocketChannel.class)
//                .option(ChannelOption.TCP_NODELAY, true)
//                .handler(new ChannelInitializer<SocketChannel>() {
//                    @Override
//                    protected void initChannel(SocketChannel ch) {
//                        ch.pipeline().addLast(new HHDDecoder())
//                                /*
//                                属于MessageToMessageEncoder的子类，负责将Java原生的byte[]类型转换为
//                                Netty的二进制容器ByteBuf
//                                用于将字节数组(byte[])编码为netty的byteBuf对象的处理器
//                                */
//                               .addLast(new ByteArrayEncoder())
//                                /*
//                                * 将接收到的ByteBuf网络二进制数据转换为Java原生的byte[]数组
//                                作为MessageToMessageDecoder的子类，实现ByteBuf→byte[]的零拷贝转换
//                                * */
//                                .addLast(new ByteArrayDecoder())
//                                .addLast(new NettyClientHandler());
//                    }
//                }).remoteAddress(host, port);
//    }

}
